package com.liuwei.proxy;

import com.liuwei.common.Invocation;
import com.liuwei.common.URL;
import com.liuwei.loadbalance.Loadbalance;
import com.liuwei.protocol.HttpClient;
import com.liuwei.register.LocalRegister;
import com.liuwei.register.MapRemoteRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

// 代理对象处理每个接口
public class ProxyFactory {

    // 用户配置
    public static <T> T getProxy(Class interfaceClass) {
        // 使用反射完成代理调用
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 服务mock
                String mock = System.getProperty("mock");
                if (mock!=null && mock.startsWith("return:")){
                    String result = mock.replace("return:","");
                    return  result;
                }
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                HttpClient httpClient = new HttpClient() ;
                // 服务发现
                List<URL> list = MapRemoteRegister.get(interfaceClass.getName());

                String result = null;
                // 服务调用
                List<URL> invokedUrls = new ArrayList<>();
                // 最大重试次数
                int max = 3;
                while(max > 0){
                    // 使用过的url下次就不使用了
                    list.remove(invokedUrls);
                    // 负载均衡
                    URL url = Loadbalance.random(list);
                    invokedUrls.add(url);
                    try {
                        result = httpClient.send(url.getHostname(),url.getPort(),invocation);
                        break;
                    }catch (Exception e){
                        if(max-- != 0){
                            System.out.println("重试机会剩余："+max);
                            // 不为零就重试
                            continue;
                        }
                        return "服务异常";
                    }
                }
                return result;
            }
        });
        return  (T) proxyInstance;
    }
}
